<?php
/**********************************************************************************
WIKINDX: Bibliographic Management system.
Copyright (C)

This program is free software; you can redistribute it and/or modify it under the terms 
of the GNU General Public License as published by the Free Software Foundation; either 
version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; 
if not, write to the 
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

The WIKINDX Team 2007
sirfragalot@users.sourceforge.net
**********************************************************************************/
/*
* CMS hooks
*
* @author Mark Grimshaw
* @version 1
* $Header $
*/

class CMS
{
// Constructor
	function CMS($db, $vars = FALSE)
	{
		$this->db = $db;
		$this->vars = $vars;
		include_once("core/session/SESSION.php");
		$this->session = new SESSION();
		include_once("core/messages/MESSAGES.php");
		$this->messages = new MESSAGES();
		include_once("core/messages/ERRORS.php");
		$this->errors = new ERRORS();
		include_once("core/html/MISC.php");
		include_once("core/html/FORM.php");
		include_once("core/template/TEMPLATE.php");
		$this->template = new TEMPLATE('content');
	}
// display pop-up
	function display()
	{
		include_once("core/html/CLOSENOMENU.php");
		$this->template->setVar('heading', $this->messages->text("heading", "cms"));
		if(!array_key_exists('id', $this->vars))
		{
			$this->template->setVar('body', $this->errors->text('inputError', 'missing'));
			new CLOSENOMENU($this->db, $this->template->process());
		}
		$id = $this->vars['id'];
		$pString = MISC::p($this->messages->text('cms', 'introduction'));
		$pString .= $this->displayTag();
		$pString .= MISC::br() . MISC::hr() . MISC::br();
		$pString .= MISC::h($this->messages->text('cms', 'displayIds'), 3);
		$pString .= TABLE::tableStart();
		$pString .= TABLE::trStart();
		$links[] = MISC::a('link', $this->messages->text('resources', 'categories'), 
			'index.php?action=cmsDisplay&method=categories&id=' . $id);
		$links[] = MISC::a('link', $this->messages->text('resources', 'keywords'), 
			'index.php?action=cmsDisplay&method=keywords&id=' . $id);
		$links[] = MISC::a('link', $this->messages->text('resources', 'creator'), 
			'index.php?action=cmsDisplay&method=creators&id=' . $id);
		$links[] = MISC::a('link', $this->messages->text('resources', 'publisher'), 
			'index.php?action=cmsDisplay&method=publishers&id=' . $id);
		$links[] = MISC::a('link', $this->messages->text('resources', 'collection'), 
			'index.php?action=cmsDisplay&method=collections&id=' . $id);
		$pString .= TABLE::td(join("&nbsp;&nbsp;&nbsp;", $links));
		if(array_key_exists('method', $this->vars))
		{
			if($this->vars['method'] == 'categories')
			{
				include_once("core/group/GROUP.php");
				$obj = new GROUP($this->db);
				foreach($obj->grabAll() as $key => $value)
					$array[] = $value . ":&nbsp;&nbsp;" . $key;
				$size = sizeof($array);
				$size = $size <= 40 ? floor($size/2) : 20;
				$pString .= TABLE::td(FORM::selectFBox(MISC::b($this->messages->text('resources', 'categories')), 
					FALSE, $array, $size));
			}
			else if($this->vars['method'] == 'keywords')
			{
				include_once("core/keyword/KEYWORD.php");
				$obj = new KEYWORD($this->db);
				foreach($obj->grabAll() as $key => $value)
					$array[] = $value . ":&nbsp;&nbsp;" . $key;
				$size = sizeof($array);
				$size = $size <= 40 ? floor($size/2) : 20;
				$pString .= TABLE::td(FORM::selectFBox(MISC::b($this->messages->text('resources', 'keywords')), 
					FALSE, $array, $size));
			}
			else if($this->vars['method'] == 'creators')
			{
				include_once("core/creator/CREATOR.php");
				$obj = new CREATOR($this->db);
				foreach($obj->grabAll() as $key => $value)
					$array[] = $value . ":&nbsp;&nbsp;" . $key;
				$size = sizeof($array);
				$size = $size <= 40 ? floor($size/2) : 20;
				$pString .= TABLE::td(FORM::selectFBox(MISC::b($this->messages->text('resources', 'creator')), 
					FALSE, $array, $size));
			}
			else if($this->vars['method'] == 'publishers')
			{
				include_once("core/publisher/PUBLISHER.php");
				$obj = new PUBLISHER($this->db);
				foreach($obj->grabAll() as $key => $value)
					$array[] = $value . ":&nbsp;&nbsp;" . $key;
				$size = sizeof($array);
				$size = $size <= 40 ? floor($size/2) : 20;
				$pString .= TABLE::td(FORM::selectFBox(MISC::b($this->messages->text('resources', 'publisher')), 
					FALSE, $array, $size));
			}
			else if($this->vars['method'] == 'collections')
			{
				include_once("core/collection/COLLECTION.php");
				$obj = new COLLECTION($this->db);
				foreach($obj->grabAll() as $key => $value)
					$array[] = $value . ":&nbsp;&nbsp;" . $key;
				$size = sizeof($array);
				$size = $size <= 40 ? floor($size/2) : 20;
				$pString .= TABLE::td(FORM::selectFBox(MISC::b($this->messages->text('resources', 'collection')), 
					FALSE, $array, $size));
			}
		}
		$pString .= TABLE::trEnd();
		$pString .= TABLE::tableEnd();
		$this->template->setVar('body', $pString);
		new CLOSENOMENU($this->db, $this->template->process());
	}
// Function form for generating CMS tag
	function displayTag()
	{
		if(array_key_exists('method', $this->vars) && ($this->vars['method'] == 'generateCmsTag'))
		{
			$this->checkInput();
			$tag = $this->generateTag();
			unset($this->vars['method']);
		}
		else
			$tag = FALSE;
		$pString = MISC::h($this->messages->text('cms', 'generateCmsTag'), 3);
		$pString .= TABLE::tableStart();
		$pString .= TABLE::trStart();
		$pString .= FORM::formHeader("cmsDisplay");
		$pString .= FORM::hidden('method', 'generateCmsTag');
		$pString .= FORM::hidden('id', $this-> vars['id']);
		$session = $this->session->getVar('setup_cmsTagStart');
		$pString .= TABLE::td(FORM::textInput($this->messages->text('cms', 'cmsTagStart'), 
			'cmsTagStart', $session, 20));
		$session = array_key_exists('cmsPageStart', $this->vars) ? $this-> vars['cmsPageStart'] : FALSE;
		$pString .= TABLE::td(FORM::textInput($this->messages->text('cms', 'pageStart'), 
			'cmsPageStart', $session, 10));
		$session = array_key_exists('cmsPageEnd', $this->vars) ? $this-> vars['cmsPageEnd'] : FALSE;
		$pString .= TABLE::td(FORM::textInput($this->messages->text('cms', 'pageEnd'), 
			'cmsPageEnd', $session, 10), FALSE, 'left');
		$session = array_key_exists('cmsPreText', $this->vars) ? $this-> vars['cmsPreText'] : FALSE;
		$pString .= TABLE::td(FORM::textInput($this->messages->text('cite', 'preText'), 
			'cmsPreText', $session, 20));
		$session = array_key_exists('cmsPostText', $this->vars) ? $this-> vars['cmsPostText'] : FALSE;
		$pString .= TABLE::td(FORM::textInput($this->messages->text('cite', 'postText'), 
			'cmsPostText', $session, 20));
		$session = $this->session->getVar('setup_cmsTagEnd');
		$pString .= TABLE::td(FORM::textInput($this->messages->text('cms', 'cmsTagEnd'), 
			'cmsTagEnd', $session, 20));
		$pString .= TABLE::trEnd();
		$pString .= TABLE::tableEnd();
// Encapsulating TABLE element from template
		$pString .= TABLE::tdEnd() . TABLE::trEnd() . TABLE::trStart() . TABLE::tdStart();
		$pString .= TABLE::tableStart();
		$pString .= TABLE::trStart();
		$pString .= TABLE::td(MISC::br() . FORM::formSubmit("Submit"));
		if($tag)
			$pString .= TABLE::td(MISC::br() . FORM::textInput($this->messages->text('cms', 'tag'), 
			FALSE, $tag, 50));
		$pString .= TABLE::trEnd();
		$pString .= TABLE::tableEnd();
		$pString .= FORM::formEnd();
		return $pString;
	}
// Generate the CMS tag
	function generateTag()
	{
		$tag = FALSE;
		if($this->vars['cmsTagStart'])
			$tag = $this->vars['cmsTagStart'];
		$tag .= ':' . $this->vars['id'];
		if($this->vars['cmsPageStart'])
		{
			$tag .= ':' . trim($this->vars['cmsPageStart']);
			if($this->vars['cmsPageEnd'])
				$tag .= '-' . trim($this->vars['cmsPageEnd']);
		}
		else if($this->vars['cmsPageEnd']) // Assume pageEnd is actually meant to be pageStart
		{
			$tag .= ':' . trim($this->vars['cmsPageEnd']);
			$this->vars['cmsPageStart'] = $this->vars['cmsPageEnd'];
			unset($this->vars['cmsPageEnd']);
		}
		if($this->vars['cmsPreText'])
		{
			$tag .= '|' . $this->vars['cmsPreText'];
			if($this->vars['cmsPostText'])
				$tag .= '`' . $this->vars['cmsPostText'];
		}
		else if($this->vars['cmsPostText'])
			$tag .= '|`' . $this->vars['cmsPostText'];
		if($this->vars['cmsTagEnd'])
			$tag .= $this->vars['cmsTagEnd'];
		return $tag;
	}
// Check input from generateTag and write database value if required.
	function checkInput()
	{
		$cmsTagChanged = FALSE;
		if($this->session->getVar('setup_cmsTagStart') != $this->vars['cmsTagStart'])
		{
			$cmsTagChanged = TRUE;
			$this->session->setVar('setup_cmsTagStart', $this->vars['cmsTagStart']);
		}
		if($this->session->getVar('setup_cmsTagEnd') != $this->vars['cmsTagEnd'])
		{
			$cmsTagChanged = TRUE;
			$this->session->setVar('setup_cmsTagEnd', $this->vars['cmsTagEnd']);
		}
		if($cmsTagChanged)
		{
			$string = base64_encode(serialize(array($this->vars['cmsTagStart'], $this->vars['cmsTagEnd'])));
			$this->db->updateSingle('WKX_users', $this->db->formatField('cmsTag') . 
				'=' . $this->db->tidyInput($string) . ' WHERE ' . $this->db->formatField('id') . 
				'=' . $this->db->tidyInput($this->session->getVar('setup_userId')));
		}
	}
// Error handling
	function badInput($error)
	{
		$this->display($error);
	}
/*********************
*
*	The following functions deal with external calls to http://..../wikindx3/cmsprint.php.  They are NOT called from within WIKINDX
*
*********************/
	
// Create SQL statement from querystring
	function getSql($db)
	{
		if(empty($_GET) || !array_key_exists('action', $_GET))
			die('Missing or incorrect queryString');
		if(($_GET['action'] != 'getRecent') && !array_key_exists('id', $_GET))
			die('Missing or incorrect queryString');
		if(array_key_exists('id', $_GET))
		{
			$ids = explode(',', $_GET['id']);
			array_walk($ids, array($db, 'tidyInput'));
		}
// $sqlMethod only used for 'getKeyword', 'getCategory' and 'getCreator'
		if(array_key_exists('sqlMethod', $_GET) && (strtolower($_GET['sqlMethod']) == 'and'))
			$sqlMethod = ' AND ';
		else
			$sqlMethod = ' OR ';
		include_once("core/sql/STATEMENTS.php");
		$stmt = new STATEMENTS($db);
		$join = $condition = FALSE;
		if($_GET['action'] == 'getResource')
		{
			$condition = ' WHERE WKX_resource.id=' . join(' OR WKX_resource.id=', $ids);
// Ignore limit in this case
			unset($_GET['limit']);
		}
		else if($_GET['action'] == 'getCategory')
		{
			$join = " LEFT JOIN " . 
				$db->formatTable("WKX_resource_category") . " ON " . 
				$db->formatField("WKX_resource.id") . "=" . 
				$db->formatField("WKX_resource_category.id");
// NB MySQL bug: http://bugs.mysql.com/bug.php?id=2047 -- append comma temporarily
			foreach($ids as $id)
				$set[] = "FIND_IN_SET(" . $id . ", CONCAT(" . $db->formatField('categories') . ", ',')" . ")";
			$condition = " WHERE (" . join(')' . $sqlMethod . '(', $set) . ')';
		}
		else if($_GET['action'] == 'getKeyword')
		{
			$join = " LEFT JOIN " . 
				$db->formatTable("WKX_resource_keyword") . " ON " . 
				$db->formatField("WKX_resource.id") . "=" . 
				$db->formatField("WKX_resource_keyword.id");
// NB MySQL bug: http://bugs.mysql.com/bug.php?id=2047 -- append comma temporarily
			foreach($ids as $id)
				$set[] = "FIND_IN_SET(" . $id . ", CONCAT(" . $db->formatField('keywords') . ", ',')" . ")";
			$condition = " WHERE (" . join(')' . $sqlMethod . '(', $set) . ')';
		}
		else if($_GET['action'] == 'getCreator')
		{
// NB MySQL bug: http://bugs.mysql.com/bug.php?id=2047 -- append comma temporarily
			foreach($ids as $id)
				$set[] = "
				FIND_IN_SET(" . $id . ", CONCAT(" . 
					$db->formatField('creator1') . ", ',')) OR 
				FIND_IN_SET(" . $id . ", CONCAT(" . 
					$db->formatField('creator2') . ", ',')) OR 
				FIND_IN_SET(" . $id . ", CONCAT(" . 
					$db->formatField('creator3') . ", ',')) OR 
				FIND_IN_SET(" . $id . ", CONCAT(" . 
					$db->formatField('creator4') . ", ',')) OR 
				FIND_IN_SET(" . $id . ", CONCAT(" . 
					$db->formatField('creator5') . ", ','))";
			$condition = " WHERE (" . join(')' . $sqlMethod . '(' , $set) . ')';
		}
		else if($_GET['action'] == 'getPublisher')
		{
// 'proceedings_article' resource type has publisher in 'miscField1' (if publisher exists)
			foreach($ids as $id)
				$set[] = "IF(" . 
				$db->formatField('type') . '=' . $db->tidyInput('proceedings_article') . 
					' AND ' . $db->formatField('miscField1') . ',' . 
				$db->formatField('miscField1') . '=' . $id . ',' . 
				$db->formatField('publisher') . '=' . $id . ')';
			$condition = " WHERE " . join(' OR ' , $set);
		}
		else if($_GET['action'] == 'getCollection')
			$condition = ' WHERE ' . $db->formatField('collection') . '=' . 
				join(' OR ' . $db->formatField('collection') . '=', $ids);
		else if($_GET['action'] == 'getRecent')
		{
			if(array_key_exists('days', $_GET))
			{
				$days = $_GET['days'];
				$condition = " WHERE DATE_SUB(CURDATE(), INTERVAL $days DAY) 
					<= " . $db->formatField('timestampAdd');
			}
			else
				$condition = FALSE;
			$order = 'timestampAdd';
			$stmt->ascDesc = 'DESC';
		}
		else
			die('Missing or incorrect queryString');
		if(!isset($order))
		{
// 'creator' is order default
			$possibleOrder = array('creator', 'title', 'year', 'timestamp');
			if(array_key_exists('order', $_GET) && (array_search($_GET['order'], $possibleOrder) !== FALSE))
				$order = $_GET['order'];
			else
				$order = 'creator';
		}
		$sql = $db->selectNoExecute(array("WKX_resource"),  
			$stmt->listFields($order), $stmt->listJoin($order, $join . $condition));
//print "$sql<P>";
		if(!$sql)
			die('Missing or incorrect queryString');
		$limit = array_key_exists('limit', $_GET) ? $_GET['limit'] : 0;
		return array($sql, $limit);
	}
// Function to query the database and return formatted entries
	function queryDb($db, $sql, $WIKINDX_CMS_BIBSTYLE, $limit)
	{
		include_once("core/styles/BIBSTYLE.php");
		$bibStyle = new BIBSTYLE($db, 'html', FALSE, $WIKINDX_CMS_BIBSTYLE);
		$items = array();
		if($limit)
			$resultSet = $db->limit($sql, $limit, 0);
		else
			$resultSet = $db->query($sql);
// Remove WIKINDX-style hyperlink class.
		$pattern = preg_quote("<a class=\"rLink\"");
		while($row = $db->loopRecordSet($resultSet))
			$items[$row['resourceId']] = preg_replace("/$pattern/", '<a', $bibStyle->process($row));
/**
Format into a serialized, base64_encoded array before printing.
*/
//print_r($items); print "<P>";
		if(!empty($items))
			return base64_encode(serialize($items));
		return FALSE; // no resources found
	}
// Parse and format a block of text with [cite]...[/cite][tags
	function parseText($db, $session, $WIKINDX_CMS_BIBSTYLE)
	{
// Set bibliographic style
		$session->setVar('setup_style', $WIKINDX_CMS_BIBSTYLE);
		if(array_key_exists('wikindxLink', $_GET) && $_GET['wikindxLink'] == 1)
			$linkToWikindxResource = TRUE;
		else
			$linkToWikindxResource = FALSE;
		include_once('core/cite/CITE.php');
		$cite = new CITE($db, FALSE);
		$address = urldecode($_GET['address']);
		$text = file_get_contents($address);
		return $cite->parseCitations($text, 'html', $linkToWikindxResource);
	}
}
?>